Repository navigation
feat(pm-stack): pm-notify edge relay + dead-man's switch — #8569 Phase 2 step 1 - #13518
Conversation
…ient (#8569 step 1) Step 1 of the Phase-2 design record's ordered split (doc/2026-11-17_design_pm8569_notifications_phase2.md): the relay skeleton + dead-man's switch. Edge (new package pm-stack/notify-relay): one Worker + singleton pm-notify Durable Object. POST /mirror/subscriptions takes the full subscription snapshot under a monotonic seq (highest wins, equal acks as duplicate, lower rejected 409); POST /heartbeat records the beat and re-arms the DO alarm at last-beat + 150s; the alarm opens exactly one silent episode and sends the stack.silent push (incident class, breakthrough) with the existing aggregator VAPID keypair — private key as a Worker secret, subscriptions never re-register; the first beat after silence sends exactly one recovered push naming the downtime. GET /status is the only read surface (no board at the edge). Web Push is WebCrypto-only (RFC 8291/8292), modeled on console/src/push.ts. One recorded widening of the design letter: an episode closes on the first beat after silence, epoch change or not — a suspended laptop resumes with the same epoch, and the design's exactly-one-down/exactly-one-recovered invariant holds under both signals (package README). Laptop (aggregator): new notify-relay client — stackEpoch per start, ~60s heartbeats, snapshot mirror kicked from the subscription routes, seq persisted in the relay state file, 409 re-adopts the edge seq from /status, all fail-soft. Inert until PM_AGG_NOTIFY_RELAY_URL is set, so this is safe to land ahead of the deploy (a separate leg, dispositioned on #8569). No schedules created or changed (the DO alarm is the design's only scheduler; the page-health-push narrowing is step 4), so doc/fleet-schedule-registry.md is untouched. No new runtime dependencies: the worker package's devDependencies mirror decision-events-worker (@cloudflare/workers-types, typescript, wrangler 4.44.0) for tests/typecheck/deploy tooling only.
- notify-relay/src/push.ts: the VAPID Authorization header line reached the branch in a mangled form (a redaction artifact in the write path) and did not parse; compute the header into a local and reference it, which is also easier to read. - aggregator/test/notify-relay.test.ts: the first-beat call-order assertion sliced URLs by segment count, which mishandles the single-segment /heartbeat path; compare pathnames instead. (First remote pass: relay suite 18/19 with the parse error the only failure; aggregator suite 64/65 with this assertion the only failure.)
WebCrypto validates an EC JWK as a set: pairing a test private scalar with the production public point is invalid keyData and the import throws (DataError), which is also exactly the loud failure a mismatched production secret should get. importVapid Signer/vapidAuthorization now take the public key explicitly (default: the production VAPID_PUBLIC_KEY, so the Worker path is unchanged), and the delivery tests sign with a consistent generated pair.
The relay suite is green (23/23); tsc flagged the two WebCrypto ECDH calls: workers-types' BufferSource wants an ArrayBuffer- backed view (pass a slice) and its deriveBits params predate the standard EcdhKeyDeriveParams shape (cast the params object). Runtime calls are the standard ones; comment says so.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 55 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6b6fc2c282
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const delivered = await this.deliver(outcome.state, "silent", buildSilentPayload(outcome.state)); | ||
| await this.save(delivered); |
There was a problem hiding this comment.
Preserve concurrent state updates while delivering pushes
If a heartbeat arrives while the alarm is awaiting push delivery, it updates the stored heartbeat but sees no silent episode because the alarm has not persisted that transition yet. When delivery completes, this wholesale save restores the old heartbeat and marks the recovered stack silent; the recovery notification is also missed. Subscription snapshots received during delivery can similarly be overwritten. The recovered-delivery branch has the same stale-state pattern. Persist and serialize episode transitions before external awaits, and record delivery results without overwriting newer state.
Useful? React with 👍 / 👎.
| const origin = req.headers.get("X-Relay-Origin"); | ||
| if (origin && origin !== state.origin) { | ||
| state = { ...state, origin }; | ||
| await this.save(state); |
There was a problem hiding this comment.
Ignore client origin headers on the public status route
An unauthenticated caller can send GET /status with X-Relay-Origin: https://evil.example: the Worker forwards that request unchanged, and this block persists the attacker-controlled origin. If this happens after the last heartbeat before an outage, buildSilentPayload() puts the attacker's URL in the down notification. The aggregator service worker's notification-click handler opens that supplied URL without restricting its origin, allowing a public status request to redirect a trusted notification to an attacker-controlled site. Strip this header on public requests and learn the origin only from authenticated writes.
Useful? React with 👍 / 👎.
| this.ackedJson = this.pending.json; | ||
| this.pending = null; | ||
| this.syncDirty = false; |
There was a problem hiding this comment.
Retain subscription changes requested during an in-flight sync
If a subscription is added, deleted, or has its preferences changed while a snapshot POST is in flight, requestSubscriptionSync() sets syncDirty but joins the existing syncInFlight promise without scheduling another pass. When the older snapshot is acknowledged, this assignment clears that dirty flag. Subsequent heartbeats skip subscription sync entirely, so the newer subscription state never reaches the edge until another mutation or process restart. Track changes made during the current sync and rerun before clearing the dirty state.
Useful? React with 👍 / 👎.
| if (!res.ok) throw new Error(`relay snapshot POST failed: HTTP ${res.status}`); | ||
| this.ackedJson = this.pending.json; | ||
| this.pending = null; | ||
| this.syncDirty = false; |
There was a problem hiding this comment.
Detect snapshot sequence collisions after local state loss
If the local sequence file is lost while the edge holds snapshot sequence 1, startup assigns sequence 1 to the current subscriptions. The edge treats that equal sequence as a duplicate without checking its content, so this success path marks the new content acknowledged even if the edge still holds a different subscription set. The 409 recovery path never runs, and subsequent heartbeats do not repair the mirror. The same collision can occur when restoring an older counter. Reconcile the edge sequence before assigning a fresh snapshot, or reject equal-sequence requests whose content differs.
Useful? React with 👍 / 👎.
| const classKeys = Object.keys(classes); | ||
| if (classKeys.length > MAX_CLASS_KEYS || classKeys.some((k) => typeof classes[k] !== "boolean")) { | ||
| return { ok: false, error: `subscriptions[${index}].classes must map at most ${MAX_CLASS_KEYS} keys to booleans` }; |
There was a problem hiding this comment.
Align the class-map limit with valid aggregator subscriptions
A subscription with nine custom class keys is valid in the aggregator: mergeClasses() in aggregator/src/alerts.ts adds up to 16 custom keys on top of the eight defaults in notifications.ts. buildSnapshotBody() copies that complete map unchanged, but this check permits only 16 keys total. Consequently, one valid subscription with 17 keys causes the entire snapshot, including other devices, to be rejected with HTTP 400 indefinitely. Heartbeats still succeed while new subscriptions and preference changes never reach the edge. Align this bound with the aggregator's accepted class-map representation.
Useful? React with 👍 / 👎.
#8569 Phase 2, step 1 of 4 — relay skeleton + dead-man's switch
Implements step 1 of the design record's ordered split (
doc/2026-11-17_design_pm8569_notifications_phase2.md§5). This PR deliberately does not close #8569: steps 2–4 are filed as #13468 (event mirror), #13469 (edge answer intake), #13470 (cron narrowing), and the production deploy leg is dispositioned on the issue (below).Edge — new package
pm-stack/notify-relayOne Worker (
pm-notify) + one singleton Durable Object, following thedecision-events-workerprecedent (wrangler shape, DO idiom, timing-safe shared-secret auth):POST /mirror/subscriptions— full-snapshot replace under a monotonicsnapshotSeq: higher stores, equal acks as duplicate, lower is rejected 409 and loudly (the client re-adopts the edge's seq from/status).POST /heartbeat— records{stackEpoch, seq, at}, re-arms the DO alarm at last-beat + 150 s (the alarm is the only scheduler), and returns the pending-answer count (0 until step 3 — the field exists now so the client contract is stable).stack.silentepisode per silence and sends the down push (payload classincident, breakthrough — quiet hours are never consulted at the edge); the first beat after silence sends exactly one recovered push naming the downtime. Silence is measured from the last beat, so both numbers describe the true silent span.GET /status— up/silent/since + heartbeat/snapshot/delivery facts. Deliberately not board data; everything else 404s (the answer routes are step 3, the event mirror is step 2).pm-stack/console/src/push.ts: the existing aggregator keypair sends from the edge, the private key arriving as a Worker secret — no new keypair, no subscription re-registration. A410is counted, never deleted locally: the mirror is never the record.Laptop — aggregator relay client
src/notify-relay.ts:stackEpochminted per start; a ~60 s heartbeat loop; the subscription snapshot mirrored on start and whenever the store changes — the two/api/push/subscriptionsroutes now kickrequestNotifyRelaySubscriptionSync(). The seq persists in~/.local/state/pm-aggregator/notify-relay.json; a failed POST retries with the same seq and content; a 409 re-adopts the edge's seq.pm-aggregator.notify-relay-shared-secret); the VAPID private key name is unchanged. Everything is fail-soft: a dead edge, a missing secret, or an absent store is recorded on the client and never touches the throat's own sends.PM_AGG_NOTIFY_RELAY_URLunset the client never starts and the aggregator runs exactly as before, so this is safe to land ahead of the deploy.Evidence (remote dispatch, REMOTE BUILDS ONLY)
bun test23 pass / 0 fail +tsc --noEmitclean. Oracles are named per test: the RFC 8291 roundtrip decrypts the sealed body back to the payload; the VAPID JWT verifies against the signing key and names the push origin; the episode tests assert exactly-one-down / exactly-one-recovered across alarm re-fires, epoch-change recovery, same-epoch resume, and a second episode.bun test test/notify-relay.test.ts test/alerts.test.ts65 pass / 0 fail. (The package'stsc --noEmitis red on main for one pre-existing error insrc/quota-reset-duration.test.ts, untouched by this PR — filed as pm-stack/aggregator: package typecheck red on main — quota-reset-duration.test.ts(256) string|undefined vs string|null #13484. This PR's files produce no type errors.)Not in this PR
wrangler deploywith the day-to-day Cloudflare token (Bitwarden by name),wrangler secret put RELAY_SHARED_SECRET+VAPID_PRIVATE_KEY(values from the Bitwarden names in the package README), then setPM_AGG_NOTIFY_RELAY_URLin the aggregator's environment and restart it. Drew's acceptance (kill the stack → down push < 2 min; restart → exactly one recovered push) runs after that deploy.doc/fleet-schedule-registry.mdis untouched.decision-events-worker's existing set (@cloudflare/workers-types ^4.20251011.0,typescript ^5.6.0,wrangler 4.44.0) for tests/typecheck/deploy tooling only; the aggregator gains no dependency.Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.